package space.panker916.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import space.panker916.annotation.LoginRequired;
import space.panker916.event.EventProducer;
import space.panker916.pojo.Event;
import space.panker916.pojo.R;
import space.panker916.pojo.User;
import space.panker916.service.LikeService;
import space.panker916.utils.HostHolder;
import space.panker916.utils.RedisKeyUtil;

import java.util.HashMap;
import java.util.Map;

import static space.panker916.utils.Constants.ENTITY_TYPE_POST;
import static space.panker916.utils.Constants.TOPIC_LIKE;

@Controller
public class LikeController {

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/like")
    @ResponseBody
    @LoginRequired
    // 给 帖子点赞 or 给评论点赞 ？？？
    public R like(int entityType, int entityId, int entityUserId, int postId) {
        User user = hostHolder.getUser();

        // 点赞操作
        likeService.like(user.getId(), entityType, entityId, entityUserId);
        // 赞的数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        // 状态（当前用户是否点过赞） 点赞返回1，没点返回0，点踩返回-1
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);

        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);

        // 触发点赞事件（也许可以写成一个 service 方法来封装 ？？）
        if (likeStatus == 1) {
            Event event = new Event();
            event.setTopic(TOPIC_LIKE);
            event.setUserId(hostHolder.getUser().getId());
            event.setEntityType(entityType);
            event.setEntityId(entityId);
            event.setEntityUserId(entityUserId);
            event.setData("postId", postId);
            eventProducer.fireEvent(event);
        }

        if (entityType == ENTITY_TYPE_POST) {
            // 计算帖子分数
            String postScoreKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(postScoreKey, postId);
        }

        return new R(0, null, map);
    }
}
